package member.model.dao;

import java.sql.SQLException;
import java.util.List;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import member.domain.Member;

@Repository
public class MemberDAOMybatisImpl implements MemberDAO {

	/*
	 * SqlSessionTemplet : 마이바티스의 SqlSession의 역할을 함 - SqlSession의 JDBC 관련 메소드와
	 * 같은 메소드들을 제공 - SqlSession과의 차이점은 Transaction(커밋, 롤백) 처리에 있다.( 마이바티스에서
	 * 트랜잭션은 SqlSession에서 직접 처리했는데 SqlSessionTemplate은 스프링 컨테이너에게 맞긴다! 이 차이를
	 * 기억해라. 탬플릿은 생성자를 통해 SQLSessionFactoryBean을 통해 주입받는다. 팩토리빈은
	 * SqlSessionFactory를 생성하는 객체다.
	 */

	private SqlSessionTemplate session;

	@Autowired
	public void setSqlSessionTemplate(SqlSessionTemplate session) {
		this.session = session;
	}

	@Override
	public int insertMember(Member member) throws SQLException {
		return session.insert(makeSqlId("insertMember"), member);
	}

	@Override
	public int updateMember(Member member) throws SQLException {
		return session.insert(makeSqlId("updateMember"), member);
	}

	@Override
	public int deleteMemberById(String id) throws SQLException {
		return session.insert(makeSqlId("deleteMemberById"), id);
	}

	@Override
	public Member selectMemberById(String id) throws SQLException {
		return session.selectOne(makeSqlId("selectMemberById"), id);
	}

	@Override
	public List<Member> selectMemberList() throws SQLException {
		return session.selectList(makeSqlId("selectMemberList"));
	}

	@Override
	public List<Member> selectMemberByName(String name) throws SQLException {
		return session.selectList(makeSqlId("selectMemberByName"), name);
	}

	private String makeSqlId(String id) {
		return "member.manager." + id;
	}
}
